package com.taoism.utils;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 实体类转换工具
 *
 * @author 李嘉
 * @version 1.0
 * @Description 实体类转换工具
 * @date 2019-05-13 15:13
 */
public class EntityUtils {

    /**
     * 实体类转Map
     *
     * @param object 实体对象
     * @return
     */
    public static Map<Object, Object> entityToMap(Object object) {
        Map<Object, Object> map = new HashMap<>();
        for (Field field : object.getClass().getDeclaredFields()) {
            try {
                field.setAccessible(true);
                Object objValue = field.get(object);
                map.put(field.getName(), objValue);
                field.setAccessible(false);
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
        return map;
    }

    /**
     * Map转实体对象
     *
     * @param map    map值
     * @param entity 实体对象
     * @param <T>
     * @return
     */
    public static <T> T mapToEntity(Map<Object, Object> map, Class<T> entity) {
        T t = null;
        try {
            t = entity.newInstance();
            for (Field field : entity.getDeclaredFields()) {
                if (map.containsKey(field.getName())) {
                    field.setAccessible(true);
                    Object objValue = map.get(field.getName());
                    if (objValue != null && field.getType().isAssignableFrom(objValue.getClass())) {
                        field.set(t, objValue);
                    }
                    field.setAccessible(false);
                } else {
                    if (field.getName().equalsIgnoreCase("id")) {
                        field.setAccessible(true);
                        field.set(t, CustomUtil.GenerateID());
                        field.setAccessible(false);
                    }
                }
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return t;
    }

    /**
     * 将map转换到集合
     *
     * @param list  list集合map
     * @param clazz 类对象
     * @param <T>
     * @return
     */
    public static <T> List<T> mapToList(List<?> list, Class<T> clazz) {
        List<T> arrayList = new ArrayList<>();
        for (int i = 0; i < list.size(); i++) {
            try {
                T obj = mapToEntity((Map<Object, Object>) list.get(i), clazz);
                arrayList.add(obj);
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
        return arrayList;
    }
}
